package me.zhengjie.modules.service.impl;

import cn.hutool.core.date.DateTime;
import com.qiniu.util.Json;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.domain.Api;
import me.zhengjie.modules.domain.ApiBatch;
import me.zhengjie.modules.domain.Batch;
import me.zhengjie.modules.domain.Companies;
import me.zhengjie.modules.domain.enterprise.EnterpriseInformation;
import me.zhengjie.modules.domain.intellectual.IntellectualVo;
import me.zhengjie.modules.domain.intellectual.Qualification;
import me.zhengjie.modules.repository.ApiBatchMapper;
import me.zhengjie.modules.repository.ApiMapper;
import me.zhengjie.modules.repository.BatchMapper;
import me.zhengjie.modules.repository.CompaniesMapper;
import me.zhengjie.modules.repository.enterprise.EnterpriseInfMapper;
import me.zhengjie.modules.repository.intellectual.*;
import me.zhengjie.modules.service.EnterIntIntellectualService;
import me.zhengjie.modules.utils.Contents;
import me.zhengjie.modules.utils.JsonUtils;
import me.zhengjie.modules.utils.MyHttpUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("EnterIntIntellectualService")
@RequiredArgsConstructor
public class EnterIntIntellectualServiceImpl implements EnterIntIntellectualService {

    private final EnterIntTrademarkMapper trademarkMapper;
    private final EnterIntSoftwareMapper softwareMapper;
    private final EnterIntWorksMapper worksMapper;
    private final EnterIntWebSiteMapper webSiteMapper;
    private final EnterIntPatentMapper patentMapper;
    private final EnterpriseQuaMapper quaMapper;

    private final CompaniesMapper companiesMapper;

    private final ApiMapper apiMapper;
    private final BatchMapper batchMapper;
    private final ApiBatchMapper apiBatchMapper;

    /**
     * 添加企业知识产权信息，如果有异常则回滚
     * @param intellectualVo
     */
    @Transactional
    @Override
    public void addIntellectualByIntellectualVo(IntellectualVo intellectualVo) {
        trademarkMapper.insertTrademarkByList(intellectualVo.getTrademarkList());
        softwareMapper.insertSoftwareByList(intellectualVo.getSoftwareList());
        worksMapper.insertWorksByList(intellectualVo.getWorksList());
        webSiteMapper.insertWebsiteByList(intellectualVo.getWebsiteList());
        patentMapper.insertPatentByList(intellectualVo.getPatentList());
    }

    @Transactional
    //@Scheduled(fixedDelay = 1000*24*60*60,initialDelay=1000*60*1)
    public void AutoAddIntellectualByIntellectualVo(){
        Api api=apiMapper.selectApiByVariableName("BASIC_ENTERPRISE_INTEL");
        ApiBatch apiBatches=apiBatchMapper.selectApiBatchByApiId(api.getId());
        if(apiBatches!=null){
            //apiBatches不为空的情况，说明有查到数据，在这个基础上判断是否满足执行周期
            //满足执行周期则重新获取一次
            //不满足则跳过 结束方法
            Date now=new Date();
            long poor=now.getTime()-apiBatches.getCreateTime().getTime();
            System.out.println(poor);
            long day= (long)api.getCycle()*24*60*60*1000;
            System.out.println(day);
            if(poor>day){
                //到执行周期了
                System.out.println("执行新一轮的企业知识产权数据添加");
                Long batchId= util.SnowFlakeUtil.getSnowFlakeId();
                List<Companies> companiesList=companiesMapper.selectAll();
                if(companiesList!=null&&companiesList.size()>0){
                    for (Companies c : companiesList) {
                        IntellectualVo intellectualVo=JsonUtils.JsonToIntellectualVo(MyHttpUtils.GetJson(Contents.token,"http://open.api.tianyancha.com/services/open/cb/ipr/3.0?keyword="+c.getCompanyName()));
                        List<Qualification> qualifications=JsonUtils.JsonToQualification(MyHttpUtils.GetJson(Contents.token,"http://open.api.tianyancha.com/services/open/m/certificate/2.0?name="+c.getCompanyName()+"&pageSize=20&pageNum=1"),c.getCompanyName());
                        if(qualifications!=null&&qualifications.size()>0){
                            qualifications.forEach(i->{
                                i.setBatchId(batchId);
                                i.setCompaniesId(c.getId());
                            });
                            quaMapper.AutoInsertEnterpriseQuaByList(qualifications);
                        }
                        if(intellectualVo!=null){
                            if(intellectualVo.getPatentList().size()>0){
                                intellectualVo.getPatentList().forEach(i->{
                                    i.setCompaniesId(c.getId());
                                    i.setBatchId(batchId);
                                });
                                patentMapper.AutoInsertPatentByList(intellectualVo.getPatentList());
                            }
                            if(intellectualVo.getSoftwareList().size()>0){
                                intellectualVo.getSoftwareList().forEach(i->{
                                    i.setCompaniesId(c.getId());
                                    i.setBatchId(batchId);
                                });
                                softwareMapper.AutoInsertSoftwareByList(intellectualVo.getSoftwareList());
                            }
                            if(intellectualVo.getTrademarkList().size()>0){
                                intellectualVo.getTrademarkList().forEach(i->{
                                    i.setCompaniesId(c.getId());
                                    i.setBatchId(batchId);
                                });
                                trademarkMapper.AutoInsertTrademarkByList(intellectualVo.getTrademarkList());
                            }
                            if(intellectualVo.getWebsiteList().size()>0){
                                intellectualVo.getWebsiteList().forEach(i->{
                                    i.setCompaniesId(c.getId());
                                    i.setBatchId(batchId);
                                });
                                webSiteMapper.AutoInsertWebsiteByList(intellectualVo.getWebsiteList());
                            }
                            if(intellectualVo.getWorksList().size()>0){
                                intellectualVo.getWorksList().forEach(i->{
                                    i.setCompaniesId(c.getId());
                                    i.setBatchId(batchId);
                                });
                                worksMapper.AutoInsertWorksByList(intellectualVo.getWorksList());
                            }
                        }
                    }
                    Batch batch=new Batch();
                    batch.setCreateTime(new DateTime());
                    batch.setBatchNo(batchId);
                    batchMapper.insertBatch(batch);
                    ApiBatch apiBatch=new ApiBatch();
                    apiBatch.setApiId(api.getId());
                    apiBatch.setBatchId(batchId);
                    apiBatch.setCreateTime(new DateTime());
                    apiBatchMapper.insertApiBatch(apiBatch);
                }
            }else{
                //执行周期没到，直接结束方法运行
                return;
            }
        }else{
            //apiBatches为空的情况 说明这个数据集是第一次执行，数据库中没有数据
            //这种情况要从天眼查获取第一轮数据
            System.out.println("知识产权->暂无数据");
            Long batchId= util.SnowFlakeUtil.getSnowFlakeId();
            List<Companies> companiesList=companiesMapper.selectAll();
            if(companiesList!=null&&companiesList.size()>0){
                for (Companies c : companiesList) {
                    //IntellectualVo intellectualVo=JsonUtils.JsonToIntellectualVo(MyHttpUtils.GetJson(Contents.token,"http://open.api.tianyancha.com/services/open/cb/ipr/3.0?keyword="+c.getCompanyName()));
                    IntellectualVo intellectualVo=JsonUtils.JsonToIntellectualVo(Contents.d);
                    //List<Qualification> qualifications=JsonUtils.JsonToQualification(MyHttpUtils.GetJson(Contents.token,"http://open.api.tianyancha.com/services/open/m/certificate/2.0?name="+c.getCompanyName()+"&pageSize=20&pageNum=1"),c.getCompanyName());
                    List<Qualification> qualifications=JsonUtils.JsonToQualification(Contents.f);
                    if(qualifications!=null&&qualifications.size()>0){
                        qualifications.forEach(i->{
                            i.setBatchId(batchId);
                            i.setCompaniesId(c.getId());
                        });
                        quaMapper.AutoInsertEnterpriseQuaByList(qualifications);
                    }
                    if(intellectualVo!=null){
                        if(intellectualVo.getPatentList().size()>0){
                            intellectualVo.getPatentList().forEach(i->{
                                i.setCompaniesId(c.getId());
                                i.setBatchId(batchId);
                            });
                            patentMapper.AutoInsertPatentByList(intellectualVo.getPatentList());
                        }
                        if(intellectualVo.getSoftwareList().size()>0){
                            intellectualVo.getSoftwareList().forEach(i->{
                                i.setCompaniesId(c.getId());
                                i.setBatchId(batchId);
                            });
                            softwareMapper.AutoInsertSoftwareByList(intellectualVo.getSoftwareList());
                        }
                        if(intellectualVo.getTrademarkList().size()>0){
                            intellectualVo.getTrademarkList().forEach(i->{
                                i.setCompaniesId(c.getId());
                                i.setBatchId(batchId);
                            });
                            trademarkMapper.AutoInsertTrademarkByList(intellectualVo.getTrademarkList());
                        }
                        if(intellectualVo.getWebsiteList().size()>0){
                            intellectualVo.getWebsiteList().forEach(i->{
                                i.setCompaniesId(c.getId());
                                i.setBatchId(batchId);
                            });
                            webSiteMapper.AutoInsertWebsiteByList(intellectualVo.getWebsiteList());
                        }
                        if(intellectualVo.getWorksList().size()>0){
                            intellectualVo.getWorksList().forEach(i->{
                                i.setCompaniesId(c.getId());
                                i.setBatchId(batchId);
                            });
                            worksMapper.AutoInsertWorksByList(intellectualVo.getWorksList());
                        }
                    }
                }
                Batch batch=new Batch();
                batch.setCreateTime(new DateTime());
                batch.setBatchNo(batchId);
                batchMapper.insertBatch(batch);
                ApiBatch apiBatch=new ApiBatch();
                apiBatch.setApiId(api.getId());
                apiBatch.setBatchId(batchId);
                apiBatch.setCreateTime(new DateTime());
                apiBatchMapper.insertApiBatch(apiBatch);
            }
        }
    }

    @Override
    public Map<String, Object> queryIntellectual() {
        List<String> date=patentMapper.selectPatentPubDate();
        Map<String, Object> m=new HashMap<>();
        List<Map<String, Object>> list=null;
        Map<String, Object> map=null;
        for (String s : date) {
            list=new ArrayList<>();
            map=new HashMap<>();
            map.put("patentTotal",patentMapper.selectPatentByYearToTotal(s));
            map.put("softwareTotal",softwareMapper.selectSoftwareByYearToTotal(s));
            map.put("trademarkTotal",trademarkMapper.selectTrademarkByYearToTotal(s));
            map.put("quaTotal",quaMapper.selectEnterpriseQuaByYearTotal(s));
            list.add(map);
            m.put(s,list);
        }
        return m;
    }
}
